package consulService

import (
	"fmt"
	consulapi "github.com/hashicorp/consul/api"
)

// GetServiceAddressFromConsul 从consul获取服务地址
func GetServiceAddressFromConsul(serviceName string) (string, error) {
	config := consulapi.DefaultConfig()
	//consul地址
	config.Address = "127.0.0.1:8500"
	client, err := consulapi.NewClient(config)
	if err != nil {
		return "", fmt.Errorf("failed to create Consul client: %w", err)
	}
	services, _, err := client.Health().Service(serviceName, "", true, &consulapi.QueryOptions{})
	if err != nil {
		return "", fmt.Errorf("failed to query Consul: %w", err)
	}
	if len(services) == 0 {
		return "", fmt.Errorf("no instance found for service %s", serviceName)
	}

	fmt.Printf("services: %+v\n", services)
	//获取第一个可用实例的地址和端口
	service := services[0]
	address := fmt.Sprintf("%s:%d", service.Service.Address, service.Service.Port)
	return address, nil
}
